import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import ts from "typescript";

import { resolve } from "path";
import { watch, readFileSync, writeFileSync } from "fs";
import { apiUrl } from "./src/util/static";

export default defineConfig({
  css: {
    preprocessorOptions: {
      scss: {
        api: "modern-compiler",
        silenceDeprecations: ['legacy-js-api'],
      }
    }
  },
  plugins: [vue()],
  base: "./",
  resolve: { alias: { "@/": resolve(__dirname, "./src/") + "/" } },
  assetsInclude: ["**/*.woff2"],

  server: {
    // fs: { strict: false },
    proxy: {
      "/api": {
        target: apiUrl, //目标域名
        changeOrigin: true, //需要代理跨域
        secure: false,
        rewrite: (path) => path.replace(/^\/api/, ""),
      },
      "/upload": {
        target: apiUrl, //目标域名
        changeOrigin: true, //需要代理跨域
        secure: false,
      },
      "/login": {
        target: apiUrl, //目标域名
        changeOrigin: true, //需要代理跨域
        secure: false,
      },
      "/file": {
        target: apiUrl, //目标域名
        changeOrigin: true, //需要代理跨域
        secure: false,
      },
    },
    host: true,
    strictPort: false,
    open: false,
  }
});
const watchFilePath = resolve(__dirname, "./src/main.ts");
let last = "";
function getExgs() {
  const
    sourceFile = ts.createSourceFile(watchFilePath, readFileSync(watchFilePath, "utf-8"), ts.ScriptTarget.Latest),
    ret: string[] = [];
  for (const node of sourceFile.statements) {
    if (ts.isVariableStatement(node)) {
      for (const v of node.declarationList.declarations) {
        if (ts.isIdentifier(v.name) && v.name.escapedText == "exg" && v.initializer && ts.isObjectLiteralExpression(v.initializer)) {
          for (const p of v.initializer.properties) {
            if (p.name && ts.isIdentifier(p.name)) {
              ret.push(p.name.escapedText.toString());
            }
          }
          return ret;
        }
      }
    }
  }
  return ret;
}

function watchFilePlugin() {
  const auto = getExgs(), autoType: string[] = [];
  if (JSON.stringify(auto) != last) {
    last = JSON.stringify(auto);
    auto.forEach((s, i) => {
      autoType.push(`type ${s} = typeof exg.${s};`);
      auto[i] = `${s}: AutoType.${s}`;
    });
    writeFileSync(resolve(__dirname, "./src/AutoType.d.ts"), `import { exg } from "./main";\ndeclare namespace AutoType {\n  ${autoType.join("\n  ")}\n}\nexport = AutoType;\nexport as namespace AutoType;`);
    writeFileSync(resolve(__dirname, "./src/Auto.d.ts"), `declare module globalThis {\n   const\n    ${auto.join(",\n    ")};\n}`);
  }
}
watch(watchFilePath, { persistent: true }, watchFilePlugin);
watchFilePlugin();